#include "ccstring.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

struct string *string_new(char *str) {
  struct string *S = malloc(sizeof(*S));
  S->len = strlen(str);
  S->chs = malloc(S->len + 1); // TODO 了解一下是否需要给\0留空间
  strcpy(S->chs, str);
  return S;
}

struct string *string_value_of(int num) {
  struct string *S = malloc(sizeof(*S));
  char str[11];
  sprintf(str, "%d", num);
  S->len = strlen(str);
  S->chs = malloc(S->len + 1); // TODO 了解一下是否需要给\0留空间
  strcpy(S->chs, str);
  return S;
}

struct string *string_append(struct string *S, char *str) {
  int str_len = strlen(str);
  S->chs = realloc(S->chs, S->len + str_len + 1);
  // 连接字符串。strncat函数因为编程语言特性在大批量连接字符串这个场景下不适用，此处学习参考了其他编程语言的成功经验。
  char *p = S->chs + S->len; // 连接前的字符串末尾
  int i = 0;
  for (; i < str_len; i++) {
    p[i] = str[i];
  }
  p[i] = '\0';
  S->len += str_len;
  return S;
}

bool string_equals(struct string *S, struct string *another) {
  if (S == NULL && another == NULL) {
    return true;
  } else if (S == NULL || another == NULL) {
    return false;
  }
  if (S->len != another->len) {
    return false;
  }
  return strcmp(S->chs, another->chs) == 0 ? true : false;
}

void string_free(struct string *S) {
  free(S->chs);
  free(S);
}